//
//  ZyaFeedOrderController.swift
//  SlaughterClient
//
//  Created by Zhouweibin on 2018/1/26.
//  Copyright © 2018年 zwb. All rights reserved.
//

import UIKit

class ZyaFeedOrderController: UITableViewController {
    
    private var order = [[ZyaFeedOrder]]()
    private var isShowPrice = false
    private var isOpens = [Bool]()
    private var isUpdateOrder = false

    var backModeArrClosure:(([ZyaFeedOrder])->())?
    var selectOrder = [ZyaPurchaseDetail]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 90
        tableView.separatorStyle = .none
        tableView.backgroundColor = Theme.tableViewColor
        tableView.register(ZyaFeedOrderCell.self, forCellReuseIdentifier: ZyaFeedOrderCell.identifier)
        tableView.register(ZyaFeedHeader.self, forHeaderFooterViewReuseIdentifier: ZyaFeedHeader.identifier)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "shopping"), style: .plain, target: self, action: #selector(addToShoppingCart))
        
        KSNetwork.shared.doRequest(API.getBrand,showHud: false, successHandle: { (data:ZyaBrand) in
    
               
                    self.isShowPrice = data.showprice == 1 ? true : false
                    
                    if self.selectOrder.count > 0 {
                        
                        self.isUpdateOrder = true
                        
                        let t = data.info!.map({ (tOrder) -> ZyaFeedOrder in
                            for item in self.selectOrder {
                                if item.sGoodsNm == tOrder.brandNm {
                                    tOrder.isSelected = true
                                    tOrder.amount = item.sAmountT ?? ""
                                    tOrder.idKey = item.idKey ?? ""
                                    tOrder.vouId = item.vouId
                                }
                            }
                            return tOrder
                        })
                        
                        self.order = sortObjects(t) { $0.cbTypeNm == $1.cbTypeNm }
                        
                        let v = self.order
                        let c = v.compactMap({ (item) -> Int in
                            let a = item.filter { $0.isSelected }
                            if a.count > 0 {
                                return 1
                            } else {
                                return 0
                            }
                        })
                        
                        self.isOpens = [Bool](repeating: false, count: c.count)
                        
                        for i in 0..<c.count {
                         
                            if c[i] == 1 {
                                self.isOpens[i] = true
                            } else {
                                self.isOpens[i] = false
                            }
                            
                        }
                        
                    } else {
                        self.order = sortObjects(data.info!) { $0.cbTypeNm == $1.cbTypeNm }
                        self.isOpens = [Bool](repeating: false, count: self.order.count)
                        if self.isOpens.count > 0 {
                            self.isOpens[0] = true
                        }
                    }
                    
                    self.tableView.reloadData()
           
            
            
        })

    }
    
    @objc private func addToShoppingCart() {
        
        let tOrder = order.flatMap { $0 }
        
        let data = tOrder.filter { $0.isSelected }
        guard data.count > 0 else {
            KSToast("请选择商品")
            return
        }
        
        let vc = ZyaFeedOrderAddAmountController()
         if let clo = self.backModeArrClosure {
            vc.backModeArrClosure = { arr in
                 clo(arr)
                 self.navigationController?.popViewController(animated: true)
            }
        }
         vc.order = data
        vc.isShowPrice = isShowPrice
        vc.isUpdateOrder = isUpdateOrder
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension ZyaFeedOrderController {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return order.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isOpens[section] {
            return order[section].count 
        } else {
            return 0
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: ZyaFeedOrderCell.identifier) as? ZyaFeedOrderCell else { fatalError() }
        cell.selectGoodsAction = {
            tableView.reloadData()
        }
        cell.model = order[indexPath.section][indexPath.row]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        order[indexPath.section][indexPath.row].isSelected = !order[indexPath.section][indexPath.row].isSelected
        tableView.reloadData()
    }
    
    // 显示头部
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        guard order.count != 0 else {
            return nil
        }
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: ZyaFeedHeader.identifier) as! ZyaFeedHeader
        header.label.text = order[section].first!.cbTypeNm
        header.tag = section
        header.touchUpInside = { tag in
            self.isOpens[tag] = !self.isOpens[tag]
            let indexSet = IndexSet(integer: tag)
            self.tableView.reloadSections(indexSet, with: UITableView.RowAnimation.none)
            if self.isOpens[tag] {
                self.tableView.scrollToRow(at: IndexPath(row: 0, section: tag), at: UITableView.ScrollPosition.none, animated: true)
            }
        }
        return header
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
}


